package com.example.mycomposelesson.ui.viewmodel

import androidx.compose.runtime.State
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.mycomposelesson.util.SerialUtil
import kotlinx.coroutines.launch
import mu.KotlinLogging


class MainActivityViewModel: ViewModel() {
    private val  logger=KotlinLogging.logger(this.javaClass.simpleName)
    private val _serialdata=MutableLiveData<String>()
    val serialdata:LiveData<String>
    get() = _serialdata


    private val _serialdataList = mutableStateListOf("")
    val serialdataList: SnapshotStateList<String>
    get()=_serialdataList
   // val serialdataList:LiveData<MutableList<String>>
   // get() = _serialdataList

    var nowdata:String=""

    init {
        if( SerialUtil.serialPortManager== null){
            SerialUtil.reInitSerialPort()
        }
        SerialUtil.serialPortManager!!.setOnSerialPortDataListener {
            try {
                val weights=String(it)
                weights.split("\r\n").forEach {weightstr->
                    if(weightstr.startsWith("wn")&&weightstr.endsWith("kg")){
                        val weightTest=weightstr.replace("wn","").replace("kg","")
                        setSerialData("$weightTest kg")
                    }
                }
            }catch (e:Exception){
                logger.error("串口接收数据异常",e)
            }
        }
    }

    private fun setSerialData(data:String)
    {
        if(data!=nowdata){
            nowdata=data
            logger.error{"接收到测量重量=${nowdata}"}
            viewModelScope.launch {
                _serialdata.value=data
                _serialdataList.add(data)
            }
            logger.error{"_serialdataList size=${_serialdataList.size}"}

        }

    }

}